import {login, logout, getInfo, getMenuList} from '@/api/user'
import { getToken, setToken, removeToken } from '@/utils/auth'
import { resetRouter } from '@/router'
import Layout from "@/layout/index.vue";

const getDefaultState = () => {
  return {
    token: getToken(),
    name: '',
    avatar: '',
    router:undefined,
  }
}

const state = getDefaultState()

const mutations = {
  RESET_STATE: (state) => {
    Object.assign(state, getDefaultState())
  },
  SET_TOKEN: (state, token) => {
    state.token = token
  },
  SET_NAME: (state, name) => {
    state.name = name
  },
  SET_AVATAR: (state, avatar) => {
    state.avatar = avatar
  },
  SET_ROUTER: (state, router) => {
    state.router = router
  },
  RESET_ROUTER:(state) =>{
    state.router = undefined
  }
}

const loadView = (view) => {
  if (process.env.NODE_ENV === 'development') {
    return (resolve) => require([`@/views${view}`], resolve)
  } else {
    // 使用 import 实现生产环境的路由懒加载
    return () => import(`@/views${view}`)
  }
}

// 正常来说是需要修改数据库增加夫菜单数据的，但是秉承着咋简单咋来的操作就这么写就完事儿了
// 如果需要增加重定向则修改一下返回的对象就行了{ title:'学生',icon: 'dashboard'}，吧这个改成 meta：{}, redirect:''
// 然后在下方get中增加行了
// 不需要重定向写法
const routerNameMap = new Map([
  ['/student',{ title:'学生',icon: 'dashboard'}],
  ['/teacher',{ title:'老师',icon: 'dashboard'}],
  ['/Administrator',{ title:'管理员',icon: 'dashboard'}],
])

// // 需要
// const routerNameMap = new Map([
//   ['/pupil',{ meta:{title:'学生',icon: 'dashboard'}, redirect: '/pupil/achievements' }],
//   ['/teacher',{ meta:{title:'老师',icon: 'dashboard'} }],
//   ['/Administrator',{ meta:{title:'管理员',icon: 'dashboard'} }],
// ])

const actions = {
  // 用户登录
  login({ commit }, userInfo) {
    const { username, password } = userInfo
    return new Promise((resolve, reject) => {
      // username.trim 删除前面和后面的空格
      login({ username: username.trim(), password: password }).then(res => {
        let data = res.message
        // 将token值同步到Vuex
        commit('SET_TOKEN', data)
        // 设置公共的token值
        setToken(data)
        resolve()
      }).catch(error => {
        reject(error)
      })
    })
  },

  getRouter({ commit }){

    return new Promise(( resolve, reject ) =>  {
          getMenuList().then( res =>{
            let data = res.data

            // 存储path
            let tempPrefix = []

            //获取path前缀
            data.forEach( v =>{
              let path = v.path.split("/")[1]
              tempPrefix.push( path )
            })

            // 为path去重
            const prefixArray = Array.from(new Set( tempPrefix ));

            // 构造路由对象
            // 父级路由
            let routers = prefixArray.map( d=>{

              const path = "/" + d
              return {
                path,
                component: Layout,
                children: [],
                name: d.substring(0,1).toUpperCase() + d.substring(1),
                meta:routerNameMap.get( path ), // 不需要重定向写法
                // ...routerNameMap.get( path ) // 需要重定向写法
              }
            })

            // 子级路由
            routers.forEach( route=>{

              data.forEach( item =>{

                if( route.path === "/" + item.path.split("/")[1] ){

                  let name = item.name

                  route.children.push({
                    path: item.path,
                    component: loadView( item.url ),
                    // name: name.substring(0,1).toUpperCase() + name.substring(1),
                    meta: { title: item.label , icon: item.icon },
                  })
                }
              })
            })

            commit('SET_ROUTER', routers )

            resolve(routers)
          }).catch(error => {
            reject(error)
          })
    })
  },

  // 获取用户信息
  getInfo({ commit, state }) {
    return new Promise((resolve, reject) => {
      // 根据token值获取用户的基本信息
      // code:状态码,data:用户基本信息
      getInfo(state.token).then(res => {
        let data = res.data
        // data中没有数据
        if (!data) {
          return reject('验证失败,请重新登录。')
        }

        const { username, avatar } = data

        // 将 用户名 同步到Vuex
        commit('SET_NAME', username)
        // 将 用户头像 同步到Vuex
        commit('SET_AVATAR', avatar)
        resolve(data)
      }).catch(error => {
        reject(error)
      })
    })
  },

  // 用户退出
  logout({ commit, state }) {
    return new Promise((resolve, reject) => {
      logout(state.token).then(() => {
        removeToken() // 必须先删除令牌
        resetRouter()
        // 将 用户信息 同步到Vuex
        commit('RESET_STATE')
        commit('RESET_ROUTER')
        resolve()
      }).catch(error => {
        reject(error)
      })
    })
  },

  // 删除token
  resetToken({ commit }) {
    return new Promise(resolve => {
      removeToken() // 删除令牌(必须先删除令牌)
      commit('RESET_STATE')
      resolve()
    })
  },
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}

